import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router'

const request = axios.create({
  baseURL: 'http://localhost:8880',
  timeout: 3000
})
request.interceptors.request.use(config => {
  if (!config.headers) {
    config.headers = {}
  }
  const auth = sessionStorage.getItem('auth')
  if (auth) {
    config.headers.Authorization = auth
  }
  if (config.method === 'post') {
    config.data = JSON.stringify(config.data)
    config.headers['Content-Type'] = 'application/json'
  }
  return config
}, err => {
  console.log(err)
  ElMessage.error('请求错误')
  return Promise.reject(err)
})
request.interceptors.response.use(resp => {
  if (resp.data.code === 200) {
    return Promise.resolve(resp)
  } else {
    ElMessage.error(resp.data.msg)
    if (resp.data.code === 401) {
      router.replace('/login').then(r => {
        return Promise.reject(r)
      })
    }
    return Promise.reject(resp)
  }
}, err => {
  ElMessage.error('请求失败')
  console.log(err)
  return Promise.reject(err)
})
request.defaults.withCredentials = true
export default request
